package com.example.springsecurity03.service;

import com.example.springsecurity03.entity.Role;
import com.example.springsecurity03.entity.User;
import com.example.springsecurity03.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author:
 * @DATE:2023/7/3 9:28
 * @Description:
 * @Version 1.0
 */
@Component
@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private  UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.loadUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名有误！");
        }
        List<Role> roles = userMapper.getRolesByUserId(user.getId());
        user.setRoles(roles);
        return user;
    }
}
